package com.wuyi.tea.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuyi.tea.domain.dto.ProductDTO;
import com.wuyi.tea.domain.pojo.*;
import com.wuyi.tea.domain.vo.CommentVO;
import com.wuyi.tea.domain.vo.ProductVO;
import com.wuyi.tea.domain.vo.UserVO;
import com.wuyi.tea.enums.ConstantEnum;
import com.wuyi.tea.mapper.*;
import com.wuyi.tea.service.CommentService;
import com.wuyi.tea.service.ProductService;
import com.wuyi.tea.util.LocalStorageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private PictureMapper pictureMapper;

    @Resource
    private OrderProductMapper orderProductMapper;

    @Resource
    private CommentService commentService;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private CartProductMapper cartProductMapper;

    @Transactional
    @Override
    public void addProduct(ProductDTO productDTO) {

        // 校验
        if (!StringUtils.hasText(productDTO.getName())||productDTO.getCategoryId()==null
            ||productDTO.getPrice()==null||productDTO.getSaleStatus()==null
            ||productDTO.getOverCount()==null){
            throw new RuntimeException("请检查传递的数据是否完整");
        }

        // 1.将商品的基本属性添加到商品表
        Product product = BeanUtil.copyProperties(productDTO,Product.class);

        productMapper.insert(product);

        List<String>pictures = productDTO.getPictures();
        if (CollectionUtils.isEmpty(pictures)){
            return;
        }
        // 如果商品的主图片为空，则将第一张介绍图片设置为主图片
        if (!StringUtils.hasText(product.getMainPicture())){
            product.setMainPicture(pictures.get(0));
            productMapper.updateById(product);
        }

        // 2.将商品表的相关图片存入到图片表
        for ( String url: pictures) {
            Picture picture = Picture.builder()
                    .orientId(product.getId())               // 设置商品的id
                    .picture(url)                           //  设置url
                    .orient(ConstantEnum.ORIENT_PRODUCT)    // 设置图片属于商品
                    .build();
            pictureMapper.insert(picture);
        }
    }


    @Transactional
    @Override
    public void deleteProduct(List<Integer> ids) {
        // 如果要删除的商品个数为0
        if (CollectionUtils.isEmpty(ids)){
            return;
        }

        for (Integer productId : ids) {
            // 1.删除商品相关的所有介绍图片
            pictureMapper.delete(new LambdaQueryWrapper<Picture>()
                    .eq(Picture::getOrient,ConstantEnum.ORIENT_PRODUCT)
                    .eq(Picture::getOrientId,productId)
            );

            // 2. 找到该商品的所有评论
            List<Comment> comments = commentService.list(new LambdaQueryWrapper<Comment>()
                    .eq(Comment::getOrient,ConstantEnum.ORIENT_PRODUCT)
                    .eq(Comment::getOrientId,productId)
            );

            // 3.删除评论相关的所有图片
            for (Comment comment : comments) {

                pictureMapper.delete(new LambdaQueryWrapper<Picture>()
                        .eq(Picture::getOrient,ConstantEnum.ORIENT_COMMENT)
                        .eq(Picture::getOrientId,comment.getId())
                );

                // 4.删除商品相关的所有评论
                commentService.removeById(comment.getId());
            }


            // 5.删除所有购物车中的该商品
            cartProductMapper.delete(new LambdaQueryWrapper<CartProduct>()
                    .eq(CartProduct::getProductId,productId)
            );

            //  6.删除所有该订单中的当前商品
            orderProductMapper.delete(new LambdaQueryWrapper<OrderProduct>()
                    .eq(OrderProduct::getProductId,productId)
            );

            // 7.删除商品
            productMapper.deleteById(productId.toString());
        }

    }

    @Override
    public Page<ProductVO> list(String key, Integer saleStatus, Long categoryId, Integer priceMin, Integer priceMax, Integer page, Integer pageSize) {

        // 分页查询
        Page<Product> productPage = productMapper.selectPage(
                new Page<>(page, pageSize,false),
                new LambdaQueryWrapper<Product>()
                        .like(StringUtils.hasText(key),Product::getName,key)
                        .eq(Objects.nonNull(saleStatus),Product::getSaleStatus,saleStatus)
                        .eq(Objects.nonNull(categoryId),Product::getCategoryId,categoryId)
                        .ge(Objects.nonNull(priceMin),Product::getPrice,priceMin)
                        .le(Objects.nonNull(priceMax),Product::getPrice,priceMax)
        );
        List<Product> products = productPage.getRecords();

        // 3.将product对象转换为productVo对象
        List<ProductVO>productVOS=new ArrayList<>();
        for (Product product : products) {
            ProductVO productVO = BeanUtil.copyProperties(product,ProductVO.class);

            // 找到该商品的所有图片
            List<Picture> pictures = pictureMapper.selectList(
                    new LambdaQueryWrapper<Picture>()
                            .eq(Picture::getOrient,ConstantEnum.ORIENT_PRODUCT)
                            .eq(Picture::getOrientId,product.getId())
            );
            productVO.setPictures(pictures);
            productVOS.add(productVO);
        }
        Page<ProductVO> productVOPage = new Page<>(page,pageSize,productPage.getTotal());
        productVOPage.setRecords(productVOS);
        return productVOPage;
    }


    @Transactional
    @Override
    public void updateProduct(ProductDTO productDTO) {

        // 1. 删除商品所有相关的介绍图片
        pictureMapper.delete(new LambdaQueryWrapper<Picture>()
                .eq(Picture::getOrient,ConstantEnum.ORIENT_PRODUCT)
                .eq(Picture::getOrientId,productDTO.getId())
        );

        // 2. 添加所有新的介绍图片
        if (CollectionUtils.isEmpty(productDTO.getPictures())){
            return;
        }
        for (String url : productDTO.getPictures()) {

            Picture picture = Picture.builder()
                    .picture(url)
                    .orient(ConstantEnum.ORIENT_PRODUCT)
                    .orientId(productDTO.getId())
                    .build();
            pictureMapper.insert(picture);
        }

        // 3.更新商品的其他信息
        if (!StringUtils.hasText(productDTO.getMainPicture())){
            productDTO.setMainPicture(productDTO.getPictures().get(0));
        }
        Product product = BeanUtil.copyProperties(productDTO,Product.class);
        productMapper.updateById(product);
    }

    @Override
    public List<Product> selectById(Long categoryId) {

        //查询
        return productMapper.selectList(new LambdaQueryWrapper<Product>()
                        .eq(Product::getCategoryId,categoryId)
        );
    }

    @Override
    public ProductDTO listByProductId(Long productId) {
        //构建查询条件
        Product product = productMapper.selectById(productId);

        List<Picture> pictures = pictureMapper.selectList(new LambdaQueryWrapper<Picture>()
                .eq(Picture::getOrient, ConstantEnum.ORIENT_PRODUCT)
                .eq(Picture::getOrientId, productId));

        ProductDTO productDTO = BeanUtil.copyProperties(product,ProductDTO.class);

        List<String> urlList=new ArrayList<>();
        for (Picture picture : pictures) {
            urlList.add(picture.getPicture());
        }

        List<Comment> commentList = commentMapper.selectList(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getOrient, ConstantEnum.ORIENT_PRODUCT)
                .eq(Comment::getOrientId, productId));

        User user = userMapper.selectById(LocalStorageUtil.get().toString());
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);

        List<CommentVO> commentVOList=new ArrayList<>();
        for (Comment comment : commentList) {
            CommentVO commentVO= BeanUtil.copyProperties(comment,CommentVO.class);
            commentVO.setUser(userVO);
            commentVOList.add(commentVO);
        }

        productDTO.setComments(commentVOList);
        productDTO.setPictures(urlList);

        return productDTO;
    }

    @Override
    public List<ProductVO> getProductRecommend(Long categoryId) {

        // 1.查询出当前分类下所有的商品
        List<Product> products = productMapper.selectList(new LambdaQueryWrapper<Product>()
                .eq(Product::getCategoryId, categoryId)
            );

        // 2.随机选出4个进行返回
        List<ProductVO> res = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            Random random = new Random();
            int r = random.nextInt(products.size());
            Product product = products.get(r);
            ProductVO productVO = BeanUtil.copyProperties(product,ProductVO.class);
            res.add(productVO);
            products.remove(r);
        }

        return res;
    }
}
